<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 角色表格 -->
      <div>
        <!-- 添加按钮 -->
        <el-row :gutter="80">
          <el-col :span="4">
            <el-button disabled type="primary" @click="dialogFormVisible = true"  style="margin-bottom: 15px;">添加角色</el-button>
          </el-col>
        </el-row>
        <el-table :data="roleList" border stripe>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row  v-for="(item1, index1) in scope.row.children" :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']">
                <!-- 1级权限 -->
                <el-col :span="3">
                  <el-tag @close="removeRightById(scope.row, item1.id)" closable type="success"> {{ item1.authName }} </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 2、3级权限 -->
                <el-col :span="21">
                  <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="['vcenter', 'bdtop', index2 === 0 ? '' : 'bdtop']">
                    <el-col :span="6">
                      <el-tag @close="removeRightById(scope.row, item2.id)" closable> {{ item2.authName }} </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag @close="removeRightById(scope.row, item3.id)" closable type="warning" v-for="(item3, index) in item2.children" :key="index">
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" prop="level" width="300px">
            <template slot-scope="scope">
              <el-button disabled type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
              <el-button disabled type="danger" @click="deleRole(scope.row.id)" icon="el-icon-delete" size="mini">删除</el-button>
              <el-button type="warning" @click="showSetRoleDialog(scope.row)" icon="el-icon-setting" size="mini">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog @close="cleanDefKeys" title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
        <!-- 树形控件 在data中绑定props绑定文本内容: chilren、label:authname-->
        <!-- node-key用来作为树节点的唯一标识 -->
        <!-- default-expand-all默认展开所有的节点 -->
        <!-- default-checked-keys默认勾选节点的key的数组 -->
        <el-tree :data="rightList" :props="treeProps" @node-click="handleNodeClick"
        show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的树形结构中节点ID数组
      defKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    async removeRightById (role, rightid) {
      // 弹框提示
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色的权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 确定返回confirm 否则返回cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您已取消删除')
      }
      const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightid}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.info(res.meta.msg)
      // this.getRoleList()
      // 重新赋值 更新页面
      role.children = res.data
    },
    // 分配权限对话框
    async showSetRoleDialog (role) {
      const { data: res } = await this.$http.get('/rights/tree')
      this.roleId = role.id
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightList = res.data
      console.log(this.rightList)
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式获取角色下所有三级权限id 保存到defKeys
    getLeafKeys (node, arr) {
      // 如果是三级节点 没有children
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级节点 递归调用 对当前结点的所有孩子节点递归调用getLeafKeys
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    cleanDefKeys () {
      this.defKeys = []
    },
    async allotRights () {
      // ...是ES6的语法 拷贝数组内容
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(key)
      const idStr = key.join(',')
      const { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRightDialogVisible = false
      this.getRoleList()
    }
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
// 纵向居中
.vcenter {
  display: flex;
  align-items: center;
}
</style>
